package com.corpgovernment.organization.service.impl;

import com.corpgovernment.api.basic.dto.OrgDTO;
import com.corpgovernment.api.basic.enums.SourceEnum;
import com.corpgovernment.api.basic.vo.UserLoginResponseVo;
import com.corpgovernment.api.organization.enums.LoginTypeEnum;
import com.corpgovernment.api.permission.vo.GetUserPermissionListRequest;
import com.corpgovernment.common.apollo.OrganizationApollo;
import com.corpgovernment.common.base.BaseUserInfo;
import com.corpgovernment.common.base.CommonException;
import com.corpgovernment.common.base.JSONResult;
import com.corpgovernment.common.handler.ICacheHandler;
import com.corpgovernment.organization.util.OrganizationUtils;
import com.corpgovernment.permission.service.UserRoleService;
import com.corpgovernment.permission.service.UserService;
import com.corpgovernment.redis.cache.RoleResourceManager;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import static com.corpgovernment.api.basic.metadata.ELoginStatus.NO_ADMIN_PERMISSION;

/**
 * @author jhxue
 * @create 2022-02-18-14:23
 */
@Service
@Slf4j
public class AdminLoginSourceService extends AbstractLoginSourceService {

	@Autowired
	private ICacheHandler cacheHandler;
	@Autowired
	private OrganizationApollo organizationApollo;
	@Autowired
	private UserService userService;
	@Autowired
	private RoleResourceManager roleResourceManager;
	@Autowired
	private UserRoleService userRoleService;

    @Override
    public UserLoginResponseVo process(BaseUserInfo userInfo, UserLoginResponseVo response, LoginTypeEnum loginType) {
        String source = userInfo.getSource();
        Boolean isBgUser = userInfo.getBgUser();
        String token = userInfo.getToken();
        String accountName = userInfo.getAccountName();
        String uid = userInfo.getUid();
//        String identityId = source + ":" + token;
//        log.info("admin login  key :{}", identityId);
        if (isBgUser) {
            // 菜单列表(后台才有)
            List<String> menuList = userService.getAllUrlList();
            response.setMenuList(menuList);
            //3个月
//            cacheHandler.setValue(source + ":" + token, userInfo, organizationApollo.getLoginTimeOut());
            //获取当前用户的角色信息
            JSONResult<Long> roleIdByUidAndOrgId = userRoleService.findRoleIdByUidAndOrgId(null, uid);
            roleResourceManager.setUserRoleId(userInfo.getUid(), roleIdByUidAndOrgId.getData());
//            cacheHandler.setValue(identityId, userInfo, organizationApollo.getLoginTimeOut());
            log.info("用户登录uid登录成功 accountName={},token={},是否是后台用户={},menuList={}", accountName, token, isBgUser, menuList);
            return response;
        }
        // 前台用户
        // 前台用户有效的身份
        List<OrgDTO> orgList = OrganizationUtils.getOrgInfoByUid(uid);
        if (loginType == LoginTypeEnum.TICKET && StringUtils.isNotBlank(userInfo.getOrgId())) {
            // 如果此时已知用户的组织(ticket登录的情况，用户多身份会先选好组织id)，则筛选
            orgList = orgList.stream().filter(o -> StringUtils.equals(o.getDeptId(), userInfo.getOrgId(), false)).collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(orgList)) {
            throw new CommonException(NO_ADMIN_PERMISSION.getValue(), NO_ADMIN_PERMISSION.getDesc());
        }
        // 前台用户有管理权限的身份
        List<OrgDTO> adminOrgList = orgList.stream().filter(e -> CollectionUtils.isNotEmpty(OrganizationUtils.getIdentityList(uid, e.getDeptId()))).distinct().collect(Collectors.toList());
        // 无管理员权限，限制登录
        if (CollectionUtils.isEmpty(adminOrgList)) {
            throw new CommonException(NO_ADMIN_PERMISSION.getValue(), NO_ADMIN_PERMISSION.getDesc());
        } else if (adminOrgList.size() == 1) {
            // 有且仅有一个管理员权限，直接登录
            OrgDTO orgInfo = adminOrgList.get(0);
            userInfo.setCorpId(orgInfo.getCorpId()).setOrgId(orgInfo.getDeptId()).setCorpName(orgInfo.getCorpName()).setOrgName(orgInfo.getDeptName());
            List<String> menuList = userService.getAllUrlList();
            response.setMenuList(menuList).setCorpId(orgInfo.getCorpId()).setOrgId(orgInfo.getDeptId()).setCorpName(orgInfo.getCorpName()).setOrgName(orgInfo.getDeptName());
//            cacheHandler.setValue(source + ":" + token, userInfo, organizationApollo.getLoginTimeOut());
            roleResourceManager.setUserRoleId(userInfo.getUid(), CollectionUtils.isEmpty(orgInfo.getRoleIds()) ? null : orgInfo.getRoleIds().get(0));
            log.info("用户登录uid登录成功 accountName={},token={},是否是后台用户={},menuList={}", accountName, token, isBgUser, menuList);
            return response;
        } else {
            // 有多个管理员权限，让其选择身份登录
            response.setIdentityList(this.convert(adminOrgList, "待审核"));
//            String key = source + ":" + token;
//            cacheHandler.setValue(key, userInfo, 60L);
        }
        response.setSource(source);
        return response;
    }

    @Override
    public SourceEnum[] getLoginSource() {
        return new SourceEnum[]{SourceEnum.PC};
    }
}
